﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PMCSerialTransfer.Packets
{
    class RecvFilePacket : APacket
    {
        public override bool Packet(byte[] Data)
        {
            return Process(Data);
        }

        public override bool EndProcess(bool Ok)
        {
            string path;
            SerialSettings settings = new SerialSettings();
            settings.GetSettings();
            if (Ok)
            {
                Globals.FileName = System.Text.Encoding.Default.GetString(Globals.DataPacket, 0, Globals.DataPacket.Length);

                path = settings.DefaultFolder + @"\" + Globals.FileName;
                if (File.Exists(@path))
                {
                    FileInfo fi = new FileInfo(path);
                    Globals.FileStream = File.OpenRead(@path);
                    Globals.FileLen = (Int32)fi.Length;
                    byte[] lenbuff = new byte[4];
                    Globals.DataPacket = new byte[5];
                    Globals.DataPacket[0] = (byte)Globals.ACKType.E_ACK;

                    lenbuff = BitConverter.GetBytes(Globals.FileLen);
                    for (int i = 0; i < 4; i++)
                    {
                        if (BitConverter.IsLittleEndian)
                        {
                            Globals.DataPacket[i + 1] = lenbuff[3 - i];
                        }
                        else
                        {
                            Globals.DataPacket[i + 1] = lenbuff[i];
                        }
                    }
                    Globals.Create((byte)CommFactory.Command.SndACK, Globals.DataPacket);
                    Globals.Message = "Sending " + Globals.FileName + " Bytes " + fi.Length.ToString() + "\n";
                    Globals.PacketSize = 0;
                    Globals.ProgressEvent = Globals.ProgressType.Load;
                }
            }
            else
            {
                Globals.ErrorCount++;
                if (Globals.ErrorCount < 10)
                {
                    Globals.Message = "CRC Error, retrying\n";
                    Globals.DataPacket = new byte[1];
                    Globals.DataPacket[0] = (byte)Globals.ACKType.E_ERR;
                    Globals.Create((byte)CommFactory.Command.SndACK, Globals.DataPacket);
                }
                else
                {
                    Globals.Message = "Transmission Error.. aborting\n";
                    Globals.DataPacket = new byte[1];
                    Globals.DataPacket[0] = (byte)Globals.ACKType.E_ABORT;
                    Globals.FileStream.Close();
                    Globals.Create((byte)CommFactory.Command.SndACK, Globals.DataPacket);
                    Globals.ErrorCount = 0;
                }
            }
            return Ok;
        }
    }
}
